<?php

namespace app\api\service\wanlshop;

use fast\Http;
use think\Exception;

class Common
{
    private static $types = [
        'getGoodsList',
        'getGoodsDetails'
    ];

    /**
     * 获取接口数据
     * @param $type
     * @param $params
     * @return false|mixed
     */
    public static function getData($type, $params)
    {
        if (!in_array($type, self::$types) || !$params) {
            return false;
        }

        $header = [
//            'channelType:' . 'DONGHUOMUSZ',
            'channelType:' . 'DONGHUOMU',
            'md5:' . self::getSign($params)
        ];

        // 额外参数
        $option = [
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_POSTFIELDS => http_build_query($params),
            CURLOPT_POST => 1
        ];
//        $resp = Http::post("https://uat.api.weipinshang.net/mcang/Mcang/" . $type, $params, $option);
        $resp = Http::post("https://api.weipinshang.net/mcang/Mcang/" . $type, $params, $option);

        // 添加数据到数据库
        $res = json_decode($resp, true);
        if (isset($res['data']) && !empty($res['data'])) {
            return $res['data'];
        }
        return false;
    }

    /**
     * 获取签名
     * @param $params
     * @return string
     */
    protected static function getSign($params = [])
    {
        $query = [];
        ksort($params);
        foreach ($params as $key => $val) {
            $query[] = $key . "=" . $val;
        }
        $data = implode('&', $query);
//        return strtolower(md5($data . "DONGHUOMUSZ" . "4e0f57288842aa18f236b45f72d1e2a8"));//测试
        return strtolower(md5($data . "DONGHUOMU" . "ca69a0343ac66303f01d172bb86bd65c"));//正式
    }

    /**
     * 错误处理
     * @param $msg
     * @param $code
     * @return mixed
     * @throws Exception
     */
    public static function error($msg = '操作错误', $code = 4)
    {
        throw new Exception($msg, $code);
    }
}